package middleware

import (
	"fmt"
	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"manhe/tool"
	"net/http"
)

func RBAC() gin.HandlerFunc {
	adapter, _ := gormadapter.NewAdapterByDB(Gorm)
	e, _ := casbin.NewEnforcer("./config/model.conf", adapter)

	return func(c *gin.Context) {
		user := c.GetHeader("name")
		fmt.Println("获取的角色内容：", user)
		if has, err := e.Enforce(user, c.Request.RequestURI, c.Request.Method); err != nil || !has {
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
				"msg": "forbidden",
			})
		} else {
			c.Next()
		}
	}
}

//链接数据库

var Gorm *gorm.DB

func init() {
	Gorm = InitGorm()
}

func InitGorm() *gorm.DB {
	data := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", tool.CONFIG.Db.Username, tool.CONFIG.Db.Password, tool.CONFIG.Db.Ip, tool.CONFIG.Db.Host, tool.CONFIG.Db.Dbname)
	db, err := gorm.Open(mysql.Open(data), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}
	mysqlDB, err := db.DB()
	if err != nil {
		log.Fatal(err)
	}
	mysqlDB.SetMaxIdleConns(5)
	mysqlDB.SetMaxOpenConns(10)
	return db
}
